Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
// C(n, r) : choose r from n publicstaticvoidcombine(int[] nums, int depth, int r, int start, List<Integer> curr, List<List<Integer>> ans) { if (depth == r) { ans.add(newArrayList<>(curr)); return; }
for (inti= start; i < nums.length; i++) { curr.add(nums[i]); combine(nums, depth + 1, r, i + 1, curr, ans); curr.removeLast(); } }
// C(n, r) : choose r from n publicstaticvoidcombine(int[] nums, int depth, int r, int start, List<Integer> curr, List<List<Integer>> ans) { if (depth == r) { ans.add(newArrayList<>(curr)); return; }
for (inti= start; i < nums.length; i++) { curr.add(nums[i]); combine(nums, depth + 1, r, i, curr, ans); curr.removeLast(); } }
解决问题
回到问题当中,我们要求找到所有相加为 target 的可重复组合。因为不是定长,所以我们的回溯中不引入 r 这个参数。将递归的退出条件更改为 target == 0,在每次递归中减少 target 的值。